<template>
  <el-dialog
    :visible="showRoleDialog"
    title="分配角色"
    @close="$emit('update:showRoleDialog', false)"
  >
    <!-- 弹层内容 -->
    <!-- checkbox -->
    <el-checkbox-group v-model="roleIds">
      <!-- 放置n个的checkbox  要执行checkbox的存储值 item.id-->
      <el-checkbox
        v-for="item in roleList"
        :key="item.id"
        :label="item.id"
      >{{ item.name }}</el-checkbox>
    </el-checkbox-group>
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button type="primary" size="mini" @click="btnRoleOK">确定</el-button>
        <el-button size="mini" @click="$emit('update:showRoleDialog', false)">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>
<script>
import { assignRole, getEmployeeDetail, getEnableRoleList } from '@/api/employee'

export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    roleId: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      roleList: [], // 接收角色列表
      roleIds: [] // 用来双向绑定数据的
    }
  },
  watch: {
    roleId: {
      immediate: true,
      handler(newVal) {
        if (newVal !== null) {
          this.getEnableRoleList()
        }
      }
    }
  },
  created() {

  },
  methods: {
    async getEnableRoleList() {
      this.roleList = await getEnableRoleList()
      const { roleIds } = await getEmployeeDetail(this.roleId)
      this.roleIds = roleIds
    },
    // 点击角色的确定

    async btnRoleOK() {
      if (this.roleId !== null) {
        await assignRole({
          id: this.roleId,
          roleIds: this.roleIds
        })
        this.$message.success('分配用户角色成功')
        this.$emit('update:showRoleDialog', false)
      } else {
        this.$message.error('员工ID无效')
      }
    }
  }
}
</script>

<style scoped>
.el-dialog {
  width: 500px;
}
</style>
